package hezi.helper;

import hezi.common.SystemConfig;
import hezi.core.Forum;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import org.apache.log4j.Logger;

import dz.common.PropTool;

public abstract class HZDBHelper {
	
	public static Logger logger = Logger.getLogger("");
	
	static String dbfilepath = SystemConfig.getInstance().getDbPath() + PropTool.getString("forumdbfilename");
	static String archivedbfilepath = SystemConfig.getInstance().getDbPath() + "archive2.db";
	public static Connection conn;
	public static Connection archiveconn;
	
	public HZDBHelper(){
		try {
			if(conn == null){
				Class.forName("org.sqlite.JDBC");
				conn = DriverManager.getConnection("jdbc:sqlite://"+ dbfilepath);
				archiveconn = DriverManager.getConnection("jdbc:sqlite://"+ archivedbfilepath);
			}
			
			
			createTableAndIndex();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	
	public int updateColumns(String sqlstr) {
		try {
			sqlstr = sqlstr.replace("' WHERE", "', modifytime='"+System.currentTimeMillis()+"' WHERE");
			PreparedStatement prep = conn.prepareStatement(sqlstr);
			int i =  prep.executeUpdate();
			prep.close();
			return i;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static void setCountToForum(Map<String, Forum> forumsmap, Connection conn, String sql) {
		try {
			ResultSet rs;
			Statement stat = conn.createStatement();
			rs = stat.executeQuery(sql);
			while (rs.next()) {
				String forumid = rs.getString("forumid");
				int num = rs.getInt("num");
				Forum forum = forumsmap.get(forumid);
				if(forum != null){
					if(sql.contains("image")){
						if(sql.contains("WHERE")){
							forum.newimagecount = num;
						}
						else{
							forum.totalimagecount = num;
						}
					}
					else{
						if(sql.contains("WHERE")){
							forum.newpostcount = num;
						}
						else{
							forum. totalimagecount = num;
						}
					}
				}
			}
			rs.close();
			stat.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	

	public Connection getConn() {
		return conn;
	}

	abstract  public void createTableAndIndex();
}
